<template>
  <div class="student-management">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="学员姓名">
          <el-input v-model="searchForm.studentName" placeholder="输入学员姓名" clearable />
        </el-form-item>
        <el-form-item label="性别">
          <el-select 
            v-model="searchForm.gender" 
            placeholder="全部性别" 
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="item in GENDER_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄区间">
          <el-slider
            v-model="ageRange"
            range
            :min="3"
            :max="99"
            :marks="{
              3: '3岁',
              99: '99岁'
            }"
            style="width: 300px"
          />
          <div class="age-range-values">
            <span>{{ ageRange[0] }}岁 - {{ ageRange[1] }}岁</span>
          </div>
        </el-form-item>
        <el-form-item label="学员来源">
          <el-select 
            v-model="searchForm.sources" 
            multiple 
            collapse-tags
            collapse-tags-tooltip
            placeholder="全部来源" 
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in SOURCE_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学员状态">
          <el-select 
            v-model="searchForm.statuses" 
            multiple 
            collapse-tags
            collapse-tags-tooltip
            placeholder="全部状态" 
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in STATUS_OPTIONS"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入学时间">
          <el-date-picker
            v-model="searchForm.enrollDateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DDTHH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="今日生日">
          <el-switch v-model="searchForm.isTodayBirthday" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <div class="action-buttons" v-permission="['editStudent']">
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>新增学员
      </el-button>
      <!-- <el-button @click="handleImport">
        <el-icon><Upload /></el-icon>批量导入
      </el-button>
      <el-button @click="handleExport">
        <el-icon><Download /></el-icon>导出数据
      </el-button> -->
    </div>

    <!-- 学员列表 -->
    <el-card shadow="never" class="table-card">
      <el-table 
        :data="students" 
        style="width: 100%" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="studentName" label="姓名" width="120" sortable />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column v-permission="['editStudent']" prop="phone" label="联系方式" width="150" />
        <el-table-column label="性别">
          <template #default="{row}">
            {{ GENDER_OPTIONS.find(item => item.value === row.gender)?.label || '' }}
          </template>
        </el-table-column>
        <el-table-column label="学员来源" width="120">
          <template #default="{row}">
            {{ SOURCE_OPTIONS.find(item => item.value === row.source)?.label || '' }}
          </template>
        </el-table-column>
        <el-table-column label="学员状态" width="150">
          <template #default="{row}">
            <el-tag :type="STATUS_TAG_TYPE[row.status]">
              {{ STATUS_OPTIONS.find(item => item.value === row.status)?.label || '' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enrollDate" label="入学时间" width="120">
          <template #default="{row}">
            {{ parseISODateTime(row.enrollDate, {includeTime: false})  }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{row}">
            <el-button :link="true" type="primary" @click="showDetail(row)">详情</el-button>
            <el-button :link="true" type="primary" @click="showEditDialog(row)" v-permission="['editStudent']">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 学员详情对话框 -->
    <student-detail 
      v-model="detailVisible" 
      :studentData="currentStudent"
      @refresh="fetchStudents"
    />
    
    <!-- 新增/编辑对话框 -->
    <student-edit
      v-model="editVisible"
      :student-data="currentStudent"
      :mode="editMode"
      @success="fetchStudents"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload, Download, ArrowDown } from '@element-plus/icons-vue'
import { 
  GENDER_OPTIONS,
  SOURCE_OPTIONS,
  STATUS_OPTIONS,
  STATUS_TAG_TYPE
} from '@/constants/student'
import { convertToLunar, parseISODateTime } from '@/utils/dateUtils'
import StudentDetail from './StudentDetail.vue'
import StudentEdit from './StudentEdit.vue'

// 默认头像

// 搜索表单
const ageRange = ref([3, 99])

const searchForm = reactive({
  studentName: '',
  gender: '',
  minAge: null,
  maxAge: null,
  sources: [],
  statuses: [],
  enrollDateRange: [],
  isTodayBirthday: false,
  get enrollStartDate() {
    return this.enrollDateRange?.[0] || ''
  },
  get enrollEndDate() {
    return this.enrollDateRange?.[1] || ''
  }
})

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 学员列表数据
const students = ref([])
const loading = ref(false)
const selectedStudents = ref([])

// 对话框控制
const detailVisible = ref(false)
const editVisible = ref(false)
const currentStudent = ref(null)
const editMode = ref('add') // 'add' or 'edit'

import { getStudentList } from '@/api/student'

// 获取学员列表
const fetchStudents = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.size,
      studentName: searchForm.studentName,
      gender: searchForm.gender,
      minAge: ageRange.value[0],
      maxAge: ageRange.value[1],
      sources: searchForm.sources.join(','),
      statuses: searchForm.statuses.join(','),
      enrollStartDate: searchForm.enrollStartDate,
      enrollEndDate: searchForm.enrollEndDate,
      isTodayBirthday: searchForm.isTodayBirthday
    }

    if (searchForm.isTodayBirthday) {
      const today = new Date()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      params.today = `${month}-${day}`
      params.LunarToday = convertToLunar(today)
    }
    console.log(params)
    const res = await getStudentList(params)
    students.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.log(error)
    ElMessage.error('获取学员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索学员
const handleSearch = () => {
  pagination.current = 1
  fetchStudents()
}

// 重置搜索
const resetSearch = () => {
  searchForm.studentName = ''
  searchForm.gender = ''
  ageRange.value = [3, 99]
  searchForm.sources = []
  searchForm.statuses = []
  searchForm.enrollDateRange = []
  searchForm.isTodayBirthday = false
  pagination.current = 1
  fetchStudents()
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchStudents()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchStudents()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedStudents.value = selection
}

// 显示新增对话框
const showAddDialog = () => {
  editMode.value = 'add'
  currentStudent.value = null
  editVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (student) => {
  editMode.value = 'edit'
  currentStudent.value = { ...student }
  editVisible.value = true
}

// 显示详情
const showDetail = (student) => {
  currentStudent.value = { ...student }
  detailVisible.value = true
}

// 编辑成功回调
const handleEditSuccess = () => {
  fetchStudents()
}


// 批量导入
const handleImport = () => {
  ElMessage.info('批量导入功能')
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出数据功能')
}

// 格式化课程类型
// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return dateStr.split('T')[0]
}



// 初始化加载数据
onMounted(() => {
  fetchStudents()
})
</script>

<style scoped>
.student-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.age-range-values {
  margin-left: 20px;
  margin-top: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
  text-align: center;
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
